﻿using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;

namespace CurrentUserDemo.Api.Extensions;

public static class ClaimsPrincipalExtensions
{
    public static int? FindUserId([NotNull] this ClaimsPrincipal principal)
    {
        var userIdOrNull = principal.Claims?.FirstOrDefault(c => c.Type == "uid");
        if (userIdOrNull == null || string.IsNullOrWhiteSpace(userIdOrNull.Value))
        {
            return null;
        }

        if (int.TryParse(userIdOrNull.Value, out int uid))
        {
            return uid;
        }

        return null;
    }

    public static string? FindUserName([NotNull] this ClaimsPrincipal principal)
    {
        var userNameOrNull = principal.Claims?.FirstOrDefault(c => c.Type == "name");
        if (userNameOrNull == null || string.IsNullOrWhiteSpace(userNameOrNull.Value))
        {
            return null;
        }

        return userNameOrNull.Value;
    }
}
